package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.audiorecordmp3demo.utils.RecorderAndPlayUtil;
import com.example.lamemp3.MP3Recorder;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.ToastUtils;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class MicActivity extends Activity {
    private ImageView audioMic;
    private ImageView playDelete;
    private ImageView playSure;
    private TextView micTip;
    private RelativeLayout micAnimation;
    private ImageView micAnimationLeft;
    private ImageView micAnimationRight;
    private TextView micAnimationtime;
    private Handler mHandler = new Handler();
    private Handler mdialogHandler = new Handler();
    private boolean isShosrt = false;
    private long startVoiceT, endVoiceT;
    public static String mMp3FileName;
    private boolean isStartRecord;
    public static int timer;
    private MediaPlayer mMediaPlayer = null;
    private ImageView lineplay;
    private Gson gson;
    private BaseApplication application;                // 应用主体
    private HttpConfig mHttpConfig;
    private static final String DIR = "yinian/LAME/mp3/";
    private Context mContext;
    private boolean mIsRecording = false;
    private boolean mIsLittleTime = false;
    private boolean mIsSendVoice = false;
    private RecorderAndPlayUtil mRecorderUtil = null;
    private TimerTask mTimerTask = null;
    private Timer mTimer = null;
    private float mSecond = 0;
    private AnimationDrawable animaleft;
    private AnimationDrawable animaRight;
    private String micUrl = "";
    private ProgressDialog mProgressDialog;
    private boolean mp3IsExist = false;
    private String micpath;
    private int mictime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_memory_card_mic);
        mContext = MicActivity.this;
        gson = new Gson();
        application = (BaseApplication) getApplication();
        mHttpConfig = new HttpConfig(MicActivity.this);
        mProgressDialog = new ProgressDialog(this);
        if (getIntent() != null) {
            mp3IsExist = getIntent().getBooleanExtra("mp3IsExist", false);
            micpath = getIntent().getStringExtra("micpath");
            mictime = getIntent().getIntExtra("mictime", 0);
        }
        initView();
    }


    private void initView() {
        mMediaPlayer = new MediaPlayer();

        audioMic = (ImageView) findViewById(R.id.mcard_audio_mic);
        lineplay = (ImageView) findViewById(R.id.mcard_audio_mic_play);
        playDelete = (ImageView) findViewById(R.id.mcard_audio_mic_del);
        playSure = (ImageView) findViewById(R.id.mcard_audio_mic_ok);
        micTip = (TextView) findViewById(R.id.mcard_audio_mic_tip);
        micAnimation = (RelativeLayout) findViewById(R.id.mcard_audio_animation);
        micAnimationLeft = (ImageView) findViewById(R.id.mcard_audio_animation_left);
        micAnimationRight = (ImageView) findViewById(R.id.mcard_audio_animation_right);
        micAnimationtime = (TextView) findViewById(R.id.mcard_audiomic_time);
        findViewById(R.id.mcard_audio_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = getIntent();
                Log.i("xjs", "close==>" + mp3IsExist);
                intent.putExtra("isOK", mp3IsExist);
                intent.putExtra("micUrl", micUrl);
                intent.putExtra("micpath", MainActivity.micpath);
                setResult(MemoryCardEditActivity.TAKE_MIC, intent);
                finish();
            }
        });
        animaleft = (AnimationDrawable) micAnimationLeft
                .getDrawable();
        animaRight = (AnimationDrawable) micAnimationRight
                .getDrawable();
        animaleft.setOneShot(false);
        animaRight.setOneShot(false);
        mRecorderUtil = new RecorderAndPlayUtil(DIR);
        mRecorderUtil.getRecorder().setHandle(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MP3Recorder.MSG_REC_STARTED:
                        // 开始录音
                        break;
                    case MP3Recorder.MSG_REC_STOPPED:
                        if (mIsSendVoice) {// 是否发送录音
                            mIsSendVoice = false;
                            // Toast.makeText(mContext, "停止录音", Toast.LENGTH_SHORT).show();
//                            mMp3FileName = mRecorderUtil.getRecorderPath();
                        }
                        mSecond = 0;
                        break;
                    case MP3Recorder.MSG_ERROR_GET_MIN_BUFFERSIZE:
                        initRecording();
                        Toast.makeText(mContext, "采样率手机不支持", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_CREATE_FILE:
                        initRecording();
                        Toast.makeText(mContext, "创建音频文件出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_REC_START:
                        initRecording();
                        Toast.makeText(mContext, "初始化录音器出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_AUDIO_RECORD:
                        initDialog();
                        initRecording();
                        Toast.makeText(mContext, "录音的时候出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_AUDIO_ENCODE:
                        initRecording();
                        Toast.makeText(mContext, "编码出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_WRITE_FILE:
                        initRecording();
                        Toast.makeText(mContext, "文件写入出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_CLOSE_FILE:
                        initRecording();
                        Toast.makeText(mContext, "文件流关闭出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_AUDIO_LENGHT_NULL:
                        initDialog();
                        initRecording();
                        doDeleteMic();
                        break;
                }
            }
        });
        audioMic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MicActivity.this, "请长按录音！", Toast.LENGTH_SHORT).show();
            }
        });
        audioMic.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startVoiceT = System.currentTimeMillis();
                isStartRecord = true;
                animaleft.start();
                animaRight.start();
                down();
                return true;
            }
        });
        try {
            audioMic.setOnTouchListener(new MyClickListener());
        } catch (Exception e) {
            e.printStackTrace();
        }
        lineplay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(micpath)) {
                    if (isStartRecord) {
                        isStartRecord = false;
                    }
                    File file = new File(mMp3FileName);
                    if (!file.exists()) {
                        Toast.makeText(MicActivity.this, "没有音乐文件！", Toast.LENGTH_SHORT).show();
                        lineplay.setVisibility(View.GONE);
                        audioMic.setVisibility(View.VISIBLE);
                        micTip.setText("按住录音");
                        return;
                    }
                }
                if (mMediaPlayer.isPlaying()) {
                    lineplay.setImageResource(R.drawable.audio_mic_play);
                    mMediaPlayer.pause();
                    animaleft.stop();
                    animaRight.stop();
                } else {
                    lineplay.setImageResource(R.drawable.audio_mic_pause);
                    mMediaPlayer.start();
                    animaleft.start();
                    animaRight.start();
                }
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                int time = mp.getDuration() / 1000;
//                micAnimationtime.setText(time + "''");
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                animaleft.stop();
                animaRight.stop();
                lineplay.setImageResource(R.drawable.audio_mic_play);
                if (mp3IsExist && !StringUtils.isEmpty(micpath)) {
                    try {
                        mp.stop();
                        mp.reset();
                        mp.setDataSource(micpath);
                        mp.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                        lineplay.setVisibility(View.GONE);
                        audioMic.setVisibility(View.VISIBLE);
                        micTip.setText("按住录音");
                        return;
                    }
                    return;
                }
                if (StringUtils.isEmpty(mMp3FileName))
                    return;
                File file = new File(mMp3FileName);
                try {
                    if (file.exists() && file.length() > 1) {
                        mp.stop();
                        mp.reset();
                        mp.setDataSource(mMp3FileName);
                        mp.prepare();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        playDelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp3IsExist && !StringUtils.isEmpty(micpath)) {
                    doDeleteMic();
                }
                if (StringUtils.isEmpty(mMp3FileName))
                    return;
                new AlertDialog.Builder(MicActivity.this).setMessage("确定删除已经录制好的语音吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                doDeleteMic();
                            }
                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).show();
            }
        });
        playSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mMp3FileName)) {
                    ToastUtils.showToast(MicActivity.this, "录音后确认!", 300);
                    return;
                }
                uploadMICfile();
            }
        });
        if (mp3IsExist && !StringUtils.isEmpty(micpath)) {
            Log.i("xjs", "222time==>" + mictime);
            lineplay.setVisibility(View.VISIBLE);
            audioMic.setVisibility(View.GONE);
            micTip.setText("试听");
            micAnimationtime.setText(TimeUtils.secToTime(timer));
            try {
                mMediaPlayer.setDataSource(micpath);
                mMediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
                lineplay.setVisibility(View.GONE);
                audioMic.setVisibility(View.VISIBLE);
                micTip.setText("按住录音");
                return;
            }
        } else {
            if (!StringUtils.isEmpty(mMp3FileName) || mp3IsExist) {
                lineplay.setVisibility(View.VISIBLE);
                audioMic.setVisibility(View.GONE);
                micTip.setText("试听");
                micAnimationtime.setText(TimeUtils.secToTime(timer));
            } else {
                lineplay.setVisibility(View.GONE);
                audioMic.setVisibility(View.VISIBLE);
                micTip.setText("按住录音");
            }
        }
    }

    private void doDeleteMic() {
        MainActivity.micpath = "";
        lineplay.setVisibility(View.GONE);
        audioMic.setVisibility(View.VISIBLE);
        animaleft.stop();
        animaRight.stop();
        micAnimationtime.setText("00:00");
        micTip.setText("按住录音");
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
        }
        mp3IsExist = false;
        mMp3FileName = "";
    }

    private void initDialog() {
        final Dialog canceldialog = new Dialog(this, R.style.dialog_remain_gift);
        final View cancelView = LayoutInflater.from(application).inflate(R.layout.yn_mic_lenght_null, null);
        cancelView.findViewById(R.id.micnull_tip_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                getAppDetailSettingIntent(MicActivity.this);
                canceldialog.dismiss();
            }
        });
        canceldialog.setContentView(cancelView);
        canceldialog.show();
    }

    private void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    private void down() {
        if (mTimer != null) mTimer.cancel();
        if (mTimerTask != null) mTimerTask.cancel();
        mSecond = 0;
        mIsRecording = true;
        mIsLittleTime = true;
        mTimerTask = new TimerTask() {
            int i = 1000;
            int j = 0;

            @Override
            public void run() {
                mIsLittleTime = false;
                mSecond += 1;
                i--;
                j += 1;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        micAnimationtime.setText(TimeUtils.secToTime(j));
                    }
                });
                if (i == 0) {
                    mIsSendVoice = true;
                    mdialogHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            // 录音结束
                            mTimer.cancel();
                            mTimerTask.cancel();
                            mIsRecording = false;
                            mRecorderUtil.stopRecording();
                        }
                    });
                }
                if (i < 0) {
                    mTimer.cancel();
                    mTimerTask.cancel();
                }
            }
        };
        mRecorderUtil.startRecording();
        mTimer = new Timer(true);
        mTimer.schedule(mTimerTask, 1000, 1000);
    }

    private void initRecording() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
        mRecorderUtil.stopRecording();
        mIsRecording = false;
        mSecond = 0;
        mRecorderUtil.getRecorderPath();
    }

    public void uploadMICfile() {
        final String micname = mMp3FileName;
        if (!StringUtils.isEmpty(micname)) {
            File file = new File(micname);
            if (!file.exists()) {
                Toast.makeText(MicActivity.this, "无效音频文件，请重录！", Toast.LENGTH_SHORT)
                        .show();
                lineplay.setVisibility(View.GONE);
                audioMic.setVisibility(View.VISIBLE);
                micTip.setText("按住录音");
                return;
            }
            if (file.length() < 1) {
                Toast.makeText(MicActivity.this, "录音过短！", Toast.LENGTH_SHORT).show();
                return;
            }
            getToken();
        } else {
            Toast.makeText(MicActivity.this, "无效音频文件，请重录！", Toast.LENGTH_SHORT)
                    .show();
            lineplay.setVisibility(View.GONE);
            audioMic.setVisibility(View.VISIBLE);
            micTip.setText("按住录音");
            return;
        }
    }

    private void getToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getMicAddress();
                        } else {
                            Toast.makeText(MicActivity.this, resToken.getMsg(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(MicActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
        LiteHttp.newApacheHttpClient(mHttpConfig).executeAsync(req);
    }


    private void getMicAddress() {
//        mProgressDialog.show();
        String prefix = mMp3FileName.substring(mMp3FileName.lastIndexOf(".") + 1);
        final String imgName = UUID.randomUUID().toString() + "." + prefix;
        application.getUploadManager().put(mMp3FileName, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        // micUrl = CommonConstants.YNQNURL + key;
                        micUrl = key;
//                        mProgressDialog.dismiss();
                        mp3IsExist = true;
//                        Intent intent = getIntent();
//                        intent.putExtra("isOK", mp3IsExist);
//                        intent.putExtra("micUrl", micUrl);
//                        setResult(MemoryCardEditActivity.TAKE_MIC, intent);
//                        finish();
                    }

                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                            }
                        }, null));
    }

    Handler flameHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj != null) {
                boolean fbb = (Boolean) msg.obj;
                if (fbb) {
                    audioMic.setVisibility(View.GONE);
                    lineplay.setVisibility(View.VISIBLE);
                    micTip.setText("试听");
                    try {
                        mMediaPlayer.reset();
                        mMediaPlayer.setDataSource(mMp3FileName);
                        mMediaPlayer.prepare();
                    } catch (IOException e) {
                        Log.e("xjs", "播放失败");
                    }
//                    playTime.setText(String.valueOf(timer) + "”");
                }
            }
        }
    };

    class MyClickListener implements View.OnTouchListener {
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    // 正常放开，接下来一般做以下事情：发送录音文件到服务器
                    if (isStartRecord) {
//                        // 停止录音
//                        isStartRecord = false;
                        // initRecording();
                        endVoiceT = System.currentTimeMillis();
                        timer = (int) ((endVoiceT - startVoiceT) / 1000);
//                        if (timer < 1) {
//                            isShosrt = true;
//                            mHandler.postDelayed(new Runnable() {
//                                public void run() {
//                                    isShosrt = false;
//                                }
//                            }, 500);
//                            return true;
//                        }
                        if (mIsRecording) {
                            initRecording();
                            mMp3FileName = mRecorderUtil.getRecorderPath();
                            Message message = new Message();
                            message.obj = true;
                            flameHandler.sendMessage(message);
                        }
                        animaleft.stop();
                        animaRight.stop();
                        lineplay.setImageResource(R.drawable.audio_mic_play);
                        uploadMICfile();
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                    // 异常放开，接下来一般做以下事情：删除录音文件
                    // 停止录音
                    micAnimationtime.setText(TimeUtils.secToTime(0));
                    isStartRecord = false;
//                    File file = new File(mRecordFileName);
//                    if (file.exists()) {
//                        file.delete();
//                    }
                    break;
            }
            return false;
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent mIntent = new Intent(ACTIONs.actionMIcText);
        mIntent.putExtra("isOK", mp3IsExist);
        mIntent.putExtra("micUrl", micUrl);
        mIntent.putExtra("micpath", MainActivity.micpath);
        sendBroadcast(mIntent);
        if (mMediaPlayer != null)
            mMediaPlayer.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

}
